//
//  SMLoctionManager.m
//  DiDi
//
//  Created by huangtie on 2017/3/19.
//  Copyright © 2017年 Sinmore. All rights reserved.
//

#import "SMLoctionManager.h"

@interface SMLoctionManager() <CLLocationManagerDelegate>

@property (nonatomic , strong) CLLocationManager *locationManager;

@property (nonatomic , strong) NSMutableArray<SMRequestLocationCompletion> *blocks;

@end
@implementation SMLoctionManager

+ (instancetype)sharedInstance
{
    static SMLoctionManager *instance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        instance = [[SMLoctionManager alloc] init];
    });
    
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.blocks = [NSMutableArray array];
    }
    return self;
}

- (CLLocationManager *)locationManager
{
    if (!_locationManager)
    {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        if (floor(NSFoundationVersionNumber) >= NSFoundationVersionNumber_iOS_8_0)
        {
            [_locationManager requestWhenInUseAuthorization];
            [_locationManager requestAlwaysAuthorization];
        }
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    }
    return _locationManager;
}

- (BOOL)isAuthorized
{
    return ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined &&
            ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||[CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways));
}

- (void)requestLocation:(SMRequestLocationCompletion)completion
{
    [self.blocks addObject:completion];
    
    [self.locationManager startUpdatingLocation];
}

- (void)requestPlacemark:(SMRequestPlacemarkCompletion)completion
{
    [self requestLocation:^(CLLocation * __nullable location, NSError * __nullable error) {
        CLGeocoder *coder = [[CLGeocoder alloc] init];
        [coder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            _lastPlacemark = [placemarks lastObject];
            completion([placemarks lastObject] , location , error);
        }];
    }];
}

- (void)uploadLocation:(CLLocationCoordinate2D)coordinate completion:(void (^)(BOOL isucess))completion
{
    
}

#pragma mark DELEGATE
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *locationold = [locations lastObject];
    CLLocationCoordinate2D coord = [[self class] smTransformFromWGSToGCJ:locationold.coordinate];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
    
    if (CLLocationCoordinate2DIsValid(location.coordinate))
    {
        [self uploadLocation:location.coordinate completion:^(BOOL isucess) {
            
        }];
        
        _lastLocation = location;
        [self.locationManager stopUpdatingLocation];
        if ([self.blocks firstObject])
        {
            SMRequestLocationCompletion completionBlock = [self.blocks firstObject];
            completionBlock(location , nil);
            [self.blocks removeObject:completionBlock];
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    [self.locationManager stopUpdatingLocation];
    if ([self.blocks firstObject])
    {
        SMRequestLocationCompletion completionBlock = [self.blocks firstObject];
        completionBlock(nil , error);
        [self.blocks removeObject:completionBlock];
    }
}

#pragma mark 纠正地理位置偏差
#define a 6378245.0
#define ee 0.00669342162296594323
#define pi 3.14159265358979324
+ (CLLocationCoordinate2D)smTransformFromWGSToGCJ:(CLLocationCoordinate2D)wgsLoc
{
    CLLocationCoordinate2D adjustLoc;
    if([[self class] smIsLocationOutOfChina:wgsLoc])
    {
        adjustLoc = wgsLoc;
    }
    else
    {
        double adjustLat = [[self class] smTransformLatWithX:wgsLoc.longitude - 105.0 withY:wgsLoc.latitude - 35.0];
        double adjustLon = [[self class] smTransformLonWithX:wgsLoc.longitude - 105.0 withY:wgsLoc.latitude - 35.0];
        double radLat = wgsLoc.latitude / 180.0 * pi;
        double magic = sin(radLat);
        magic = 1 - ee * magic * magic;
        double sqrtMagic = sqrt(magic);
        adjustLat = (adjustLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
        adjustLon = (adjustLon * 180.0) / (a / sqrtMagic * cos(radLat) * pi);
        adjustLoc.latitude = wgsLoc.latitude + adjustLat;
        adjustLoc.longitude = wgsLoc.longitude + adjustLon;
    }
    return adjustLoc;
}

//判断是不是在中国
+ (BOOL)smIsLocationOutOfChina:(CLLocationCoordinate2D)location
{
    if (location.longitude < 72.004 || location.longitude > 137.8347 || location.latitude < 0.8293 || location.latitude > 55.8271)
    return YES;
    return NO;
}

+ (double)smTransformLatWithX:(double)x withY:(double)y
{
    double lat = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x));
    lat += (20.0 * sin(6.0 * x * pi) + 20.0 *sin(2.0 * x * pi)) * 2.0 / 3.0;
    lat += (20.0 * sin(y * pi) + 40.0 * sin(y / 3.0 * pi)) * 2.0 / 3.0;
    lat += (160.0 * sin(y / 12.0 * pi) + 320 * sin(y * pi / 30.0)) * 2.0 / 3.0;
    return lat;
}

+ (double)smTransformLonWithX:(double)x withY:(double)y
{
    double lon = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x));
    lon += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0;
    lon += (20.0 * sin(x * pi) + 40.0 * sin(x / 3.0 * pi)) * 2.0 / 3.0;
    lon += (150.0 * sin(x / 12.0 * pi) + 300.0 * sin(x / 30.0 * pi)) * 2.0 / 3.0;
    return lon;
}

#pragma mark 坐标系转换
// 百度坐标转高德坐标
+ (CLLocationCoordinate2D)GCJ02FromBD09:(CLLocationCoordinate2D)coor
{
    CLLocationDegrees x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    CLLocationDegrees x = coor.longitude - 0.0065, y = coor.latitude - 0.006;
    CLLocationDegrees z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi);
    CLLocationDegrees theta = atan2(y, x) - 0.000003 * cos(x * x_pi);
    CLLocationDegrees gg_lon = z * cos(theta);
    CLLocationDegrees gg_lat = z * sin(theta);
    return CLLocationCoordinate2DMake(gg_lat, gg_lon);
}

// 高德坐标转百度坐标
+ (CLLocationCoordinate2D)BD09FromGCJ02:(CLLocationCoordinate2D)coor
{
    CLLocationDegrees x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    CLLocationDegrees x = coor.longitude, y = coor.latitude;
    CLLocationDegrees z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi);
    CLLocationDegrees theta = atan2(y, x) + 0.000003 * cos(x * x_pi);
    CLLocationDegrees bd_lon = z * cos(theta) + 0.0065;
    CLLocationDegrees bd_lat = z * sin(theta) + 0.006;
    return CLLocationCoordinate2DMake(bd_lat, bd_lon);
}

+ (BOOL)callThirdMapApp:(SMThirdMap_Code)appCode
              starCoord:(CLLocationCoordinate2D)starCoord
             endAddress:(NSString *)endAddress
               endCoord:(CLLocationCoordinate2D)endCoor
{
    BOOL isSuccess = NO;
    switch (appCode) {
        case SMThirdMap_Code_GD: {
            NSString *url = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=BGVIS1&slat=%lf&slon=%lf&sname=我的位置&did=BGVIS2&dlat=%lf&dlon=%lf&dname=%@&dev=0&m=0&t=%@",starCoord.latitude,starCoord.longitude, endCoor.latitude,endCoor.longitude,endAddress,@"2"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]])
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
                isSuccess = YES;
            }else{
                isSuccess = NO;
            }
            break;
        }
        case SMThirdMap_Code_BD: {
            NSString *url = [[NSString stringWithFormat:@"baidumap://map/direction?origin=%lf,%lf&destination=%f,%f&mode=%@&src=iosclient",starCoord.latitude,starCoord.longitude,endCoor.latitude,endCoor.longitude,@"walking"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] ;
            
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]])
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
                isSuccess = YES;
            }else{
                isSuccess = NO;
            }
            break;
        }
        case SMThirdMap_Code_TX: {
            NSString *url = [[NSString stringWithFormat:@"qqmap://map/routeplan?type=drive&fromcoord=%f,%f&tocoord=%f,%f&policy=1",starCoord.latitude,starCoord.longitude,endCoor.latitude,endCoor.longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]])
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
                isSuccess = YES;
            }else{
                isSuccess = NO;
            }
            break;
        }
        case SMThirdMap_Code_AP: {
            MKMapItem *currentLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:starCoord  addressDictionary:nil]];
            currentLocation.name =@"我的位置";
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:endCoor addressDictionary:nil]];
            NSArray *items = @[currentLocation, toLocation];
            NSDictionary *options = @{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeWalking, MKLaunchOptionsMapTypeKey: [NSNumber numberWithInteger:MKMapTypeStandard], MKLaunchOptionsShowsTrafficKey:@YES};
            isSuccess = [MKMapItem openMapsWithItems:items launchOptions:options];
            break;
        }
        default:
        break;
    }
    return isSuccess;
}

@end
